package org.shana.shortlink.admin.aop;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Aspect
@Slf4j
@Component
public class RequestLoggingAspect {

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *)")
    public void restControllerPointcut() {
    }

    @Around("restControllerPointcut()")
    public Object logRequestDetails(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取HttpServletRequest对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取请求路径、请求方式、登录IP
        String path = request.getRequestURI();
        String method = request.getMethod();
        String ip = request.getRemoteAddr();

        // 记录请求时间
        long timestamp = System.currentTimeMillis();

        // 执行目标方法
        Object result = joinPoint.proceed();

        // 计算接口响应时间
        long responseTime = System.currentTimeMillis() - timestamp;

        // 将时间戳转换为日期时间格式
        LocalDateTime operationTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedOperationTime = operationTime.format(formatter);

        // 记录请求详情
        log.info("Request Path: " + path);
        log.info("Request Method: " + method);
        log.info("Login IP: " + ip);
        log.info("Operation Time: " + formattedOperationTime);
        log.info("Response Time: " + responseTime + "ms");

        return result;
    }
}
